<?php

class Controller_Printpurchase extends Controller {

    public function before() {
        try {
            ACL::Required('checkpurchaseorder_index');
        } catch (HTTP_Exception_403 $e) {
            Message::error('sorry，你没有权限进这个目录');
            $this->request->redirect(URL::base(true));
        }
        include_once(MODPATH.'/commonapi/classes/purchaseApi.php');
        parent::before();
    }

    /*
     * 打印采购单的方法。
     */
    public function action_purchaseprint() {
        if($this->request->is_post()) {
            $ids = $this->request->post('ids');
        } else {
            $ids = $this->request->query('ids');
        }
        if(empty($ids)) {
            Message::error('未指定预约单号');
            $this->request->redirect($_SERVER['HTTP_REFERER']);
            exit;
        }
        $conditions = explode(',', $ids);
        
        // 实例化采购单。
        $purchaseprints = array();
        $info = array();
        $stores = Kohana::$config->load('vmi_warehouse')->as_array();
        foreach ($conditions as $value) {
            //yuqing 添加coin字段

            $sql = "SELECT `id`,warehouseid,`purchaseorder_date`,`supplier_id`,`purchaseid`,`pay_way`,
							`transportation_expense`,`store`,`remark`,`purchase_id`,`money`,`coin`
							FROM `purchaseorders` 
							WHERE `id`=".$value ." AND status <100";
			$po  = DB::query(Database::SELECT,$sql)->execute('newerp')->current();
            if(!$po){
                echo "<script>alert('预约单号：$value 目前状态不能打印预约单');window.close()</script>";die;
            }
            //yuqing 获取币种信息  array(3) { [1]=> string(9) "人民币" [2]=> string(6) "美元" [3]=> string(6) "港币" }
            $cointype = supplierbank::getCoins_arr();
            $po['coin'] = $cointype[$po['coin']];
            $po['storeName'] = isset($stores[$po['warehouseid']]) ? $stores[$po['warehouseid']] : '未知仓库';

            //-------------------------yuqing end ------------------------------//
            if (empty($po))
                continue;

            $sp = array();
            if (isset($po['pay_way']) and $po['pay_way'] > 0) {
                $payway_info = DB::select(array('paywayname', 'payment'))
                        ->from('payways')->where('id', '=', $po['pay_way'])
                        ->execute('newerp')
                        ->current();
                if (isset($payway_info['payment'])) {
                    $sp['payment'] = $payway_info['paywayname'];
                }
            } else {
                $sp['payment'] = "";
            }
            //获取到供应商联系人id,支付方式的id
            $relatedId = DB::query(Database::SELECT, 'SELECT id,contact_id,pay_way_id,supplier_id,payaccountinfo_id FROM purchasesupplier WHERE poid=' . $po['id'])
                            ->execute('newerp')->current();

            /**
             * 已经记录了采购选择的供应商信息
             */
            if ($relatedId and isset($relatedId['id']) and $relatedId['id'] > 0) {
                $supplier_id = $relatedId['supplier_id'];
                //该采购单创建时选择的供应商联系人
//                $contacts=Newerpclientapi::findContactById($relatedId['supplier_id']);

                /**
                 * 通过供应商联系人ID查询
                 * @author zhjx
                 */
                $contacts = Newerpclientapi::findContactById($relatedId['contact_id']);
//                var_dump($relatedId);exit();
                $sp['vPhone'] = $contacts['phone'];
                $sp['vFax'] = $contacts['fax'];
                $sp['vContact'] = $contacts['contact'];
                $sp['vMobile'] = $contacts['mobile'];

                //获取选择的供应商信息
                $supplier = supplierskus::getSuppliers(array('name,address'), array('id' => "=$supplier_id"));
//                echo "<pre>";print_r($supplier);echo "</pre>";die;
                $sp['vProviderName'] = $supplier[0]['name'];
                $sp['vAddress'] = $supplier[0]['address'];

                //获取付款帐号的信息
                $sql = "SELECT bankname,bankaccountname,bankaccount FROM payaccountinfo WHERE id=" . $relatedId['payaccountinfo_id'];
                $pay_indo = DB::query(Database::SELECT, $sql)->execute('newerp')->current();

                $sp['vAccount'] = $pay_indo['bankaccount'];
                $sp['vEstablishBank'] = $pay_indo['bankname'];
                $sp['vAccountname'] = $pay_indo['bankaccountname'];

            } else {
                //之前创建的采购单需要补齐联系人信息，支付信息、帐号信息
                $supplier_id = $po['supplier_id'];

                //获取选择的供应商信息
                $supplier = Newerpclientapi::getSuppliers(array('name,address'), array('id' => "=" . $supplier_id));
                $sp['vProviderName'] = $supplier[0]['name'];
                $sp['vAddress'] = $supplier[0]['address'];

                //查询供应商联系人
                $contacts = Newerpclientapi::getSupplierContacts($supplier_id);
                $sp['vPhone'] = $contacts[0]['phone'];
                $sp['vFax'] = $contacts[0]['fax'];
                $sp['vContact'] = $contacts[0]['contact'];
                $sp['vMobile'] = $contacts[0]['mobile'];

                //获取到支付方式
                $sql = ' SELECT bankname,bankaccountname,bankaccount FROM payaccountinfo
                JOIN supplierpayaccount
                ON payaccountinfo.id = `supplierpayaccount`.`payaccountinfo_id`
                WHERE `supplierpayaccount`.`supplier_id` ="' . $supplier_id . '" and `supplierpayaccount`.`active_status`=1';

                $pay_indo = DB::query(Database::SELECT, $sql)->execute('newerp')->current();
                $sp['vAccount'] = $pay_indo['bankaccount'];
                $sp['vEstablishBank'] = $pay_indo['bankname'];
                $sp['vAccountname'] = $pay_indo['bankaccountname'];
            }
//          --------------------------------------kdw-end----------------------------------
            $purchaseprints[] = array_merge($po, $sp);
        }



        $view = View::factory('printpurchase/index');
        $this->title = '采购单打印';
        $view->set('purchaseprints', $purchaseprints);
        $view->set('ids', $_POST['ids']?$_POST['ids']:$_GET['ids']);
        $view->set('condition', $_POST['condition']?$_POST['condition']:$_GET['condition']);
        if (empty($purchaseprints)) {
            $effect = "采购单被取消";
            $view->set('effect', $effect);
        }
        $this->response->body($view);
    }

    /*
     * 点击打印的时候自动生成创建采购付款和付款申请单。
     */

    public function action_insertdata() {
        if (isset($_POST ['ids'])) {
            $conditions = array_filter(explode(',', $_POST ['ids']));
        }
        include_once(MODPATH . '/commonapi/classes/purchaseApi.php');
        $msg = '';
        foreach ($conditions as $value) {
            include_once(MODPATH . '/common/logs.php');
            try {
                $value = trim($value);
                $sql = "SELECT * FROM `purchaseorders` WHERE id =" . $value;
                $po = DB::query(Database::SELECT, $sql)->execute('newerp')->current();
                if ($po['status'] == 100) {
                    continue;
                }
                $api = PurchaseApi::purchasePull($value);
                if($api['code']==200){
                    $pull = "UPDATE `purchaseorders` SET `is_pull`= 1 WHERE `id`= " . $value ;
                    DB::query(Database::UPDATE, $pull)->execute('newerp');
                }
                //$po['trans_fee'] = $po['money']+$po['transportation_expense'];
                //$insert ="INSERT INTO `pay_applicates`(`id`, `purchaseorder_id`,`supplier_id`, `applicant`, `status`, `add_time`, `check_time`, `money`, `remark`,`transportation_expense`) VALUES ('','".$po['id']."','".$po['supplier_id']."','".$po['purchase_id']."','10','".date('Y-m-d H:i:s',time())."','".date('Y-m-d H:i:s',time())."','".$po['money']."','','".$po['transportation_expense']."')";
                //DB::query(Database::INSERT,$insert)->execute('newerp');
                $update = "UPDATE `purchaseorders` SET `status`='20' , purchase_time = '" . date('Y-m-d H:i:s', time()) . "' WHERE `id`= " . $value . " AND status<20";
                DB::query(Database::UPDATE, $update)->execute('newerp');
                $update = "UPDATE `purchaseorder_details` SET `status` =20 WHERE `purchaseorder_id` =" . $value . " AND status < 20";
                DB::query(Database::UPDATE, $update)->execute('newerp');
                logs::purchaseorder_log($value, '打印成功');
                $msg = '打印成功，';
            } catch (Exception $e) {
//                echo $e->getMessage();
                $msg .= $value.'打印失败<br>';
            }
        }
        echo $msg;die;
    }
}
